package com.omega.exam.service.impl;

import com.alibaba.fastjson2.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.omega.exam.Exception.BaseException;
import com.omega.exam.entity.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.omega.exam.mapper.*;
import com.omega.exam.service.ExamRecordService;
import com.omega.exam.vo.ExamRankingVO;
import com.omega.exam.vo.StartExamVo;
import jakarta.annotation.Resource;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 考试记录Service实现类
 * 实现考试记录相关的业务逻辑
 */
@Service
public class ExamRecordServiceImpl extends ServiceImpl<ExamRecordMapper, ExamRecord> implements ExamRecordService {
    @Resource
    private ExamRecordMapper examRecordMapper;
    @Resource
    private AnswerRecordMapper answerRecordMapper;
    @Resource
    private PaperMapper paperMapper;
    @Resource
    private PaperQuestionMapper paperQuestionMapper;
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private QuestionAnswerMapper questionAnswerMapper;
    @Resource
    private QuestionChoiceMapper questionChoiceMapper;
    @Resource
    private CategoryMapper categoryMapper;


    @Transactional(rollbackFor = Exception.class)
    public ExamRecord addexam(StartExamVo startExamVo) {
        LambdaQueryWrapper<ExamRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ExamRecord::getExamId, startExamVo.getPaperId());
        lambdaQueryWrapper.eq(ExamRecord::getStudentName, startExamVo.getStudentName());
        lambdaQueryWrapper.eq(ExamRecord::getStatus, "进行中");
        ExamRecord examRecord1 = examRecordMapper.selectOne(lambdaQueryWrapper);
        if (examRecord1 != null) {
            System.out.println("12333");
            System.out.println(examRecord1);
            return examRecord1;
//            throw new BaseException("当前正在进行该考试");


        }

        ExamRecord examRecord = new ExamRecord();
        examRecord.setExamId(startExamVo.getPaperId());
        examRecord.setStudentName(startExamVo.getStudentName());
        examRecord.setScore(0);
        examRecord.setStartTime(LocalDateTime.now());
        examRecord.setStatus("进行中");
        examRecord.setWindowSwitches(0);
        examRecordMapper.insert(examRecord);
        return examRecord;

    }

    public ExamRecord getdetail(Integer id) {
        ExamRecord examRecord = examRecordMapper.selectById(id);
        if (examRecord == null) {
            throw new BaseException("不存在");
        }
        LambdaQueryWrapper<AnswerRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AnswerRecord::getExamRecordId, id);
        List<AnswerRecord> list = answerRecordMapper.selectList(lambdaQueryWrapper);
        if (!ObjectUtils.isEmpty(list)) {
            examRecord.setAnswerRecords(list);

        }
        Paper paper = paperMapper.selectById(examRecord.getExamId());
        List<Question> list1 = new ArrayList<>();
        List<PaperQuestion> list2 = new ArrayList<>();
        LambdaQueryWrapper<PaperQuestion> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(PaperQuestion::getPaperId, examRecord.getExamId());
        list2 = paperQuestionMapper.selectList(lambdaQueryWrapper1);
        for (PaperQuestion paperQuestion : list2) {
            Question question = questionMapper.selectById(paperQuestion.getQuestionId());
            LambdaQueryWrapper<QuestionAnswer> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(QuestionAnswer::getQuestionId, question.getId());
            QuestionAnswer questionAnswer = questionAnswerMapper.selectOne(lambdaQueryWrapper2);
            LambdaQueryWrapper<QuestionChoice> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper3.eq(QuestionChoice::getQuestionId, questionAnswer.getQuestionId());
            List<QuestionChoice> list3 = questionChoiceMapper.selectList(lambdaQueryWrapper3);
            question.setChoices(list3);

            question.setAnswer(questionAnswer);
            LambdaQueryWrapper<Category> lambdaQueryWrapper4 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper4.eq(Category::getId, question.getCategoryId());
            Category category = gettree(lambdaQueryWrapper4);
            question.setCategory(category);
            list1.add(question);
        }
        paper.setQuestions(list1);

        if (!ObjectUtils.isEmpty(paper)) {
            examRecord.setPaper(paper);
        }


        return examRecord;
    }

    public Category gettree(LambdaQueryWrapper<Category> lambdaQueryWrapper) {
        Category category = categoryMapper.selectOne(lambdaQueryWrapper);
        if (category != null) {
            LambdaQueryWrapper<Question> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(Question::getCategoryId, category.getId());
            category.setCount(questionMapper.selectCount(lambdaQueryWrapper2));
            LambdaQueryWrapper<Category> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(Category::getParentId, category.getId());
            List<Category> list = categoryMapper.selectList(lambdaQueryWrapper1);
            for (Category category1 : list) {
                category1.setCount(questionMapper.selectCount(lambdaQueryWrapper2.eq(Question::getCategoryId, category1.getId())));
            }

            category.setChildren(list);

        }
        return category;
    }

    private List<Category> getchildren(List<Category> children, Long pid) {
        List<Category> list = new ArrayList<>();
        for (Category category : children) {
            if (category.getParentId().equals(pid)) {
                category.setChildren(getchildren(children, category.getId()));
                list.add(category);
            }
        }
        return list;

    }

    @Transactional
    public void deleteexam(Integer id) {
        ExamRecord examRecord=examRecordMapper.selectById(id);
        if(examRecord.getStatus().equals("进行中")){
            throw new BaseException("进行中的考试不能删除");
        }
        removeById(id);
        LambdaQueryWrapper<AnswerRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AnswerRecord::getExamRecordId, id);
        List<AnswerRecord> list = answerRecordMapper.selectList(lambdaQueryWrapper);
        List<Long> idlist = new ArrayList<>();
        for (AnswerRecord answerRecord : list) {
            idlist.add(answerRecord.getId());
        }
        answerRecordMapper.deleteBatchIds(idlist);


    }
    public  List<ExamRankingVO> getphb(Integer paperId, Integer limit){
        return examRecordMapper.getphb(paperId,limit);
    }
} 